#include "minimap.h"
#include "map.h"
#include "objects.h"
#include "wizard.h"
#include "gfx.h"

extern unsigned int bpp;
extern unsigned int windowX;
extern unsigned int windowY;
extern unsigned int windowW;
extern unsigned int windowH;
extern Map* map;
extern Objects objects;

MiniMap::MiniMap(const int x, const int y, const int w, const int h) 
		: UI::Image(x, y, w, h, NULL) {

}

MiniMap::~MiniMap() {

}

void MiniMap::blit(SDL_Surface* surface) {
	if (isInvalidated_ == true)
		render();
	SDL_Rect dest;
	dest.x = x_;
	dest.y = y_;
	if (SDL_BlitSurface(surface_, NULL, surface, &dest) < 0) {
		std::cout << "surface blit failed:" << SDL_GetError() << "\n";
		exit(1);
	}
	isInvalidated_ = false;
}

void MiniMap::render() {
	w_ = map->getWidth() + 1;
	h_ = map->getHeight() + 1;
	if (surface_ != NULL)
		SDL_FreeSurface(surface_);
	surface_ = SDL_CreateRGBSurface(SDL_SWSURFACE, w_, h_, bpp, 0, 0, 0, 0);
	
	for (unsigned int y = 0; y < map->getHeight(); ++y) {
		for (unsigned int x = 0; x < map->getWidth(); ++x) {
			if (map->getTile(1, x, y) == 0) {
				putPixel(surface_, x, y, map->getTile(0, x, y) << 8);
			} else {
				putPixel(surface_, x, y, 0x3f3fff);
			}
		}
	}
	// draw a red square for the wizard (TEMPORARY)
	for (unsigned i = 0; i < objects.getNWizards(); ++i) {
	fillRect(surface_, objects.getWizard(i)->getX() - 1,
	         objects.getWizard(i)->getY() - 1, 3, 3, 0xff0000);
	}
	
	// draw a border to show where the screen is looking
	fillRect(surface_, windowX, windowY, windowW, 1, 0xff0000); // top
	fillRect(surface_, windowX + windowW - 1, windowY + 1, 1, windowH - 1, 0xff0000); // right
	fillRect(surface_, windowX, windowY + windowH - 1, windowW - 1, 1, 0xff0000); // bottom
	fillRect(surface_, windowX, windowY + 1, 1, windowH - 2, 0xff0000); // left
}

void MiniMap::setIsInvalidated(const bool isInvalidated) {
	isInvalidated_ = isInvalidated;
}

void MiniMap::tick() {
	isInvalidated_ = true;
}
